package de.herberlin.webapp.db;

import javax.persistence.EntityManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import de.herberlin.webapp.core.AppException;


/**
 * Service.java
 *
 * Created on 17. Oktober 2007, 21:45
 *
 * @author herberlin
 */
public class Service {
    
    private static Log logger=LogFactory.getLog(Service.class);
    
    public static void persist(Object object) {
        EntityManager em=getEntityManager();
        try {
            em.getTransaction().begin();
            em.persist(object); 
            em.flush();
            em.getTransaction().commit();
        } catch(Exception e) {
            logger.error(e,e);
            em.getTransaction().rollback();
            throw new AppException(e);
        }
    }
    
    public static void remove(Object object) {
        getEntityManager().remove(object);
    	
    }
    
    public static void perform(Operation op) {
        EntityManager em=getEntityManager();
         try {
            em.getTransaction().begin();
            op.perform(em);
            em.flush();
            em.getTransaction().commit();
        } catch(Exception e) {
            logger.error(e,e);
            em.getTransaction().rollback();
            throw new AppException(e);
        }
    }
    
    private static EntityManager getEntityManager() {
        return EntityManagerListener.getEntityManager();
    }
    
    
    public static <T> T getItem(Class<T> type, Object id) {
        return getEntityManager().find(type,id);
    }
}
